import {Component, OnInit} from '@angular/core';
import {MaintainBlueprintService} from '../../maintain-blueprint.service';
import {CommonService} from '../../../../services-common/common.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzUploadFile} from 'ng-zorro-antd/upload';

interface TRACKMODAL {
  visible: boolean;
  loading: boolean;
  orderNum: any;
  url: string;
  remark: string;
  file: any[];
}

@Component({
  selector: 'app-member-list',
  templateUrl: './member-list.component.html',
  styleUrls: ['./member-list.component.scss']
})
export class MemberListComponent implements OnInit {

  // 查询条件
  query = {
    orderNum: '',
    userId: '',
    status: [],
    goodsType: [],
    startDate: [],
    endDate: [],
    // 当前页
    page: 1,
    // 分页大小
    pageSize: 20,
  };
  // 表格数据
  listOfData = {
    page: 1,
    total: 100,
    records: []
  };
  statusOptions = [];
  wayOptions = [];
  trackList: any = [];
  trackModal: TRACKMODAL = {
    visible: false,
    loading: false,
    orderNum: '',
    url: '',
    remark: '',
    file: [],
  };
  afterSalesRefundModal = {
    visible: false,
    loading: false,
    price: null,
    remark: '',
    id: null
  };
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    // @ts-ignore
    this.trackModal.file = [file];
    return false;
  };

  constructor(
    public maintainBlueprintService: MaintainBlueprintService,
    public commonService: CommonService,
    public nzMessageService: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.getTableData();
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.getTableData();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.getTableData();
  }

  queryBtn() {
    this.query.page = 1;
    this.getTableData();
  }

  resetCondition() {
    this.query = {
      orderNum: '',
      userId: '',
      status: [],
      goodsType: [],
      startDate: [],
      endDate: [],
      page: 1,
      pageSize: 20,
    };
    this.queryBtn();
  }

  getTableData() {
    this.maintainBlueprintService.getMemberList({
      page: this.query.page,
      pageSize: this.query.pageSize,
      userId: this.query.userId,
      orderNum: this.query.orderNum,
      goodsType: this.query.goodsType.join(','),
      status: this.query.status.join(','),
      createBeginTime: this.maintainBlueprintService.formatTime(this.query.startDate[0], 'date'), // 开通时间-起始时间
      createEndTime: this.maintainBlueprintService.formatTime(this.query.startDate[1], 'date'), // 开通时间-截止时间
      expireBeginTime: this.maintainBlueprintService.formatTime(this.query.endDate[0], 'date'), // 到期时间-起始时间
      expireEndTime: this.maintainBlueprintService.formatTime(this.query.endDate[1], 'date'), // 到期时间-截止时间
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  export() {
    this.maintainBlueprintService.memberExport({
      page: this.query.page,
      pageSize: this.query.pageSize,
      userId: this.query.userId,
      orderNum: this.query.orderNum,
      goodsType: this.query.goodsType.join(','),
      status: this.query.status.join(','),
      createBeginTime: this.maintainBlueprintService.formatTime(this.query.startDate[0], 'date'), // 开通时间-起始时间
      createEndTime: this.maintainBlueprintService.formatTime(this.query.startDate[1], 'date'), // 开通时间-截止时间
      expireBeginTime: this.maintainBlueprintService.formatTime(this.query.endDate[0], 'date'), // 到期时间-起始时间
      expireEndTime: this.maintainBlueprintService.formatTime(this.query.endDate[1], 'date'), // 到期时间-截止时间
    });
  }

  cancel(id: any) {
    this.maintainBlueprintService.memberCancel(id).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('取消成功');
        this.getTableData();
      }
    });
  }

  showTrackModal(orderNum: any) {
    this.trackModal.orderNum = orderNum;
    this.trackModal.visible = true;
    this.trackList = [];
    this.maintainBlueprintService.getTrackList(orderNum).then((resL: any) => {
      this.trackList = resL.data.records;
    });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.maintainBlueprintService.fileUpload(file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      this.maintainBlueprintService.memberTrack({
        url: this.trackModal.url, // 附件url
        content: this.trackModal.remark, // 跟进内容
        type: 1, // 业务类型：1-精诚图纸
        businessNo: this.trackModal.orderNum, // 关联的业务编码：订单号
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            orderNum: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        orderNum: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  showAfterSalesRefundModal(id: any) {
    this.afterSalesRefundModal.visible = true;
    this.afterSalesRefundModal.id = id;
  }

  hideAfterSalesRefundModal() {
    this.afterSalesRefundModal = {
      visible: false,
      loading: false,
      price: null,
      remark: '',
      id: null
    };
  }

  refund() {
    if (this.afterSalesRefundModal.price === null) {
      this.nzMessageService.warning('请输入退款金额');
      return;
    }
    this.maintainBlueprintService.memberRefund({
      id: this.afterSalesRefundModal.id,
      refundPrice: this.afterSalesRefundModal.price,
      note: this.afterSalesRefundModal.remark
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideAfterSalesRefundModal();
      } else {
        this.nzMessageService.error(res.message);
      }
    });
  }
}
